package cn.lsc.exception;

import cn.lsc.enums.GlobaEnums;
import cn.lsc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//这个类时用来捕获全局异常的类
@Component
@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public JSONResult exception(Exception e){
        e.printStackTrace();
        log.info("捕获全局异常！！！"+e.getMessage());
        return JSONResult.error(GlobaEnums.Error);
    }
    @ExceptionHandler(GlobaCustomException.class)
    public JSONResult globaCustomException(GlobaCustomException e){
        e.printStackTrace();
        log.info("捕获自定义异常！！！"+e.getErrorMessager());
        return JSONResult.error(e);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult globaMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sbr = new StringBuilder();

        e.getBindingResult().getAllErrors().forEach(item->{
            sbr.append(item.getDefaultMessage()).append("!");
        });
        log.info("捕获全局异常！！！"+sbr.toString());
        return JSONResult.error(sbr.toString());
    }

}
